package com.restkeeper.response;

import com.alibaba.fastjson.JSON;
import com.restkeeper.response.exception.ExceptionResponse;
import org.springframework.core.MethodParameter;
import org.springframework.http.MediaType;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.server.ServerHttpRequest;
import org.springframework.http.server.ServerHttpResponse;
import org.springframework.web.bind.annotation.RestControllerAdvice;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyAdvice;

/**
 * 返回结果统一转换
 */
@RestControllerAdvice(basePackages = "com.restkeeper")
public class ResponseAdvisor implements ResponseBodyAdvice<Object>{
    @Override
    public boolean supports(MethodParameter methodParameter, Class<? extends HttpMessageConverter<?>> aClass) {
        return true;
    }

    @Override
    public Object beforeBodyWrite(Object o, MethodParameter methodParameter, MediaType mediaType, Class<? extends HttpMessageConverter<?>> aClass, ServerHttpRequest serverHttpRequest, ServerHttpResponse serverHttpResponse) {
        if(o == null) return new BaseResponse<Object>(null);
        if(o instanceof  com.restkeeper.utils.Result){
            return o;
        }
        if(o instanceof Boolean){
            boolean result = (boolean)o;

            return new BaseResponse<Boolean>(result,result);
//            return new BaseResponse<Boolean>(result);
        }else if(o instanceof ExceptionResponse){
            return new BaseResponse<>(400,((ExceptionResponse)o).getMsg());
        }

        //字符串要特殊处理
        if(o instanceof String){
            BaseResponse<Object> result = new BaseResponse<>(o);
            try {
                String response = JSON.toJSONString(result);
                serverHttpResponse.getHeaders().setContentType(MediaType.APPLICATION_JSON);
                serverHttpResponse.getBody().write(response.getBytes());
                return null;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return new BaseResponse<>(o);
    }
}
